package com.duleme.servlet;

import com.duleme.common.Config;
import com.duleme.common.EncodeUtils;
import com.duleme.dao.ShopDao;
import com.duleme.entity.Shop;
import com.duleme.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;

@MultipartConfig
@WebServlet(urlPatterns = "/openShop")
public class OpenShopServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EncodeUtils.setEncoding(req,resp);
        String shopName= URLDecoder.decode(req.getParameter("shopName"),"utf-8");
        User user = (User)req.getSession().getAttribute("user");
        //user.setUserId(100005);
        Part shopAvatar=req.getPart("upload");
        Shop shop=new Shop();
        shop.setShopName(shopName);
        if(shopAvatar!=null){
            String fileName=shopName+".jpg";
            shop.setShopAvatar(Config.SHOP_AVATAR_ACCESS_PATH+fileName);
            shopAvatar.write(Config.SHOP_AVATAR_SAVE_PATH+ File.separator+fileName);
        }else
            shop.setShopAvatar(Config.SHOP_DEFAULT_AVATAR_ACCESS_PATH);
        shop.setCreateTime(new Date());
        shop.setTotalSell(0);
        shop.setCount(0);
        shop.setOwnerId(user.getUserId());
        ShopDao dao=new ShopDao();
        if(dao.insertShop(shop)){
            Shop newshop=dao.findShopByName(shopName);
            req.getSession().setAttribute("shop",newshop);
            resp.sendRedirect("/shopIndex.jsp");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
